package com.blockmeta.bbs.immodule.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.CircleDetailActivity;
import com.blockmeta.bbs.immodule.activity.chat.UCGChatActivity;
import com.blockmeta.bbs.immodule.adapter.CircleForJoinAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.corebean.Impl.CircleDomainService;
import com.blockmeta.bbs.immodule.net.api.RecommendCircleApi;
import com.blockmeta.bbs.immodule.net.pojo.IMCircleEntityBook;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author airthor
 * @date 2019/3/13.
 * 加入圈子列表
 */
public class CirclesForJoinFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.rcv_circle_list)
    RecyclerView mRcvCircleList;

    private CircleForJoinAdapter mCircleAdapter;
    protected boolean isCanLoad = false;
    protected boolean isLoad = false;
    protected boolean isFirst = true;
    private List<ICircleEntry> mICircleEntries=new ArrayList<>();

    private int mGroupType=0;

    private int mGroupPage=1;

    public static CirclesForJoinFragment getFragmentInstance(Bundle args){
        CirclesForJoinFragment forJoinFragment = new CirclesForJoinFragment();
        forJoinFragment.setArguments(args);
        return forJoinFragment;
    }

    public CirclesForJoinFragment() {
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        isCanLoad = true;
        return inflater.inflate(R.layout.fragment_circles_for_join, container, false);
    }

    @Override
    public void initView() {
        Bundle bundle = getArguments();
        if (bundle!=null){
            mGroupType = bundle.getInt(Params.CIRCLE_TYPE);
        }
        mRcvCircleList.setLayoutManager(new LinearLayoutManager(mContext));
        mCircleAdapter = new CircleForJoinAdapter(R.layout.item_join_circle_list_hot,mICircleEntries);
        mCircleAdapter.bindToRecyclerView(mRcvCircleList);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_data,null);
        mCircleAdapter.setEmptyView(emptyView);
        //加入按钮点击
        mCircleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId()!=R.id.btn_join){
                    return;
                }
                joinCircle(mICircleEntries.get(position).getId(), mICircleEntries.get(position).getCircleAuthRule()
                        ,mICircleEntries.get(position).getUserLevel(), position);
            }
        });
        //条目点击
        mCircleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                boolean joinState = mICircleEntries.get(position).getJoinState();
                long circleId = mICircleEntries.get(position).getId();
                //根据加入状态跳转不同界面。已加入的跳转聊天页面；未加入的跳转圈子详情页面。
                if (joinState){
                    Intent intent = new Intent(mContext, UCGChatActivity.class);
                    intent.putExtra(Params.USER_TAG,circleId);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(mContext, CircleDetailActivity.class);
                    intent.putExtra(Params.CIRCLE_ID,circleId);
                    intent.putExtra(Params.JOIN_STATE,false);
                    startActivity(intent);
                }
            }
        });
        isCanLoad = true;
        /**初始化的时候去加载数据**/
        isCanLoadData();
    }

    //先于oncreatview执行的方法
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isCanLoad) {
            return;
        }

        if (getUserVisibleHint() && isFirst) {
            isFirst = false;
            netWork();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    protected void stopLoad() {

    }



    private void netWork() {
        if(mGroupType == 0){
            mCircleAdapter.setEnableLoadMore(false);
            RetrofitFactory.getRetrofit().create(RecommendCircleApi.class)
                    .getHotChatGroupList(AccountHelper.getUidInt())
                    .compose(RxUtil.<BaseImResponse<List<IMCircleEntityBook>>>rxSchedulerHelper())
                    .compose(RxUtil.<List<IMCircleEntityBook>>commonResult())
                    .compose(((RxAppCompatActivity)mContext).<List<IMCircleEntityBook>>bindToLifecycle())
                    .subscribe(new CommonSubscriber<List<IMCircleEntityBook>>(mContext) {
                        @Override
                        public void onNext(List<IMCircleEntityBook> imCircleEntityBooks) {
                            mICircleEntries.addAll(imCircleEntityBooks);
                            mCircleAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onError(Throwable t) {
                            super.onError(t);
                        }
                    });

        }else {
            mCircleAdapter.setOnLoadMoreListener(this,mRcvCircleList);
            normalCirclesNetWork();
        }

    }

    private void normalCirclesNetWork() {
        RetrofitFactory.getRetrofit().create(RecommendCircleApi.class)
                .getRecommendCircle(AccountHelper.getUidInt(),mGroupType,mGroupPage,10)
                .compose(RxUtil.<BaseImResponse<List<IMCircleEntityBook>>>rxSchedulerHelper())
                .compose(RxUtil.<List<IMCircleEntityBook>>commonResult())
                .compose(((RxAppCompatActivity)mContext).<List<IMCircleEntityBook>>bindToLifecycle())
                .subscribe(new CommonSubscriber<List<IMCircleEntityBook>>(mContext) {
                    @Override
                    public void onNext(List<IMCircleEntityBook> imCircleEntityBooks) {
                        mCircleAdapter.addData(imCircleEntityBooks);
                        //服务端没有回传totalpage，所以现在只能这样判断
                        if (imCircleEntityBooks.size() < 10){
                            mCircleAdapter.loadMoreEnd();
                        }else {
                            mCircleAdapter.loadMoreComplete();
                            mGroupPage++;
                        }



                    }

                    @Override
                    public void onError(Throwable t) {
                        mCircleAdapter.loadMoreFail();
                    }
                });
    }

    /**
     * 加入推荐圈子
     * @param circleId 圈子ID
     * @param circleAuthRule
     * @param position
     */
    private void joinCircle(final long circleId, int circleAuthRule, int userLevel, final int position) {

        IMApplicationContext.getCircleDomainService().joinCircle(mContext, circleId, circleAuthRule, userLevel, new CircleDomainService.CircleJoinCallBack(){

            @Override
            public void onSuccess(String message) {

                //本地更新加入状态
                ICircleEntry item = mCircleAdapter.getItem(position);
                item.setJoinState(true);
                mCircleAdapter.notifyItemChanged(position);
                RouterHelper.startActivity(mContext, RouterPath.IM_UCGChatActivity_ACTIVITY,String.valueOf(circleId));
            }

            @Override
            public void onFail() {

            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        normalCirclesNetWork();
    }
}
